package com.stox.ui.javafx.list.event.handler;

import java.util.List;

import javafx.event.EventHandler;
import javafx.scene.control.TreeItem;
import javafx.scene.input.DragEvent;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.stox.dto.AbstractModel;
import com.stox.dto.Scrip;
import com.stox.dto.WatchList;
import com.stox.ui.javafx.core.widget.AbstractModelTreeView;
import com.stox.ui.javafx.list.client.WatchListClient;
import com.stox.ui.javafx.list.widget.WatchlistCell;

@Component
public class WatchlistCellDragDroppedEventHandler implements
		EventHandler<DragEvent> {
	
	@Autowired
	private WatchListClient watchListClient;

	@Override
	public void handle(DragEvent event) {
		WatchlistCell cell = (WatchlistCell)event.getSource();
		if(!cell.getItem().getType().isSubTypeOf(WatchList.WATCHLIST_TYPE)) return;
		AbstractModelTreeView treeView = (AbstractModelTreeView)event.getGestureSource();
		List<TreeItem<AbstractModel>> treeItems = treeView.getSelectionModel().getSelectedItems();
		
		for(TreeItem<AbstractModel> treeItem : treeItems){
			if(null != treeItem.getValue() && null != cell.getItem() && 
					!treeItem.equals(cell.getTreeItem()) &&								//Check not self
					!treeItem.getParent().equals(cell.getTreeItem())){			//Check not parent
				if(treeItem.getValue().getType().isSubTypeOf(Scrip.ScripType.ANY)){		//Support moving only entries
					watchListClient.moveEntry(treeItem.getValue().getId(), treeItem.getParent().getValue().getId(), cell.getItem().getId());
					treeItem.getParent().getChildren().remove(treeItem);
					boolean hasChild = false;
					for(TreeItem<AbstractModel> item : cell.getTreeItem().getChildren()){
						if(item.getValue().equals(treeItem.getValue())){
							hasChild = true;
							break;
						}
					}
					if(!hasChild){
						cell.getTreeItem().getChildren().add(treeItem);
					}
					
				}
			}
		}
		event.setDropCompleted(true);
		event.consume();
	}
	
}
